import { Button, Grid, TextField, Snackbar } from "@material-ui/core";
import { Alert } from "@material-ui/lab";
import { useEffect, useState } from "react";
import { Point } from "../MyMap/MyMap";
import $ from 'jquery';

export interface Props {
    addPoint: (point: Point) => void;
    clearPoints: () => void;
}



export function MyPanel({ addPoint, clearPoints }: Props) {
    const [input, setInput] = useState("");
    const [error, setError] = useState(false);
    const [fail, setFail] = useState(false);
    const handleErrorClose = (reasonevent?: React.SyntheticEvent, reason?: string) => {
        if (reason === 'clickaway') {
            return;
        }

        setError(false);
    };
    const handleFailClose = (reasonevent?: React.SyntheticEvent, reason?: string) => {
        if (reason === 'clickaway') {
            return;
        }

        setFail(false);
    };
    const TransformPoint = (name: string, addPoint: (point: Point) => void) => {
        // useEffect(() => {

        $.ajax({
            url: 'https://api.map.baidu.com/geocoding/v3/?address=' + name + '&output=json&ak=GzlPHk1eLYhZhLz6fs4ebQnNOPU9mzG6',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(默认为:callback)
            jsonpCallback: "callback",//自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
            timeout: 5000,
            contentType: 'application/json; charset=utf-8',
            success: function (result: any) {
                console.log(result);
                if (result?.status === 0) {
                    addPoint(result.result.location);
                } else {
                    setError(true);
                }
            },
            error: function () {
                setFail(true)
            },
            
        })



        // }, [])
    }
    return <Grid container xs={12} spacing={3}>
        <Grid container xs={2}></Grid>
        <Grid item xs={8} >
            <TextField fullWidth value={input} onChange={(event) => setInput(event.target.value)} label="输入地址或在地图选点"></TextField>
        </Grid>
        <Grid item xs={2} >
            <Button onClick={() => TransformPoint(input, addPoint)} variant="contained" color="primary" >添加地址</Button>
            <Button onClick={() => clearPoints()} variant="contained" color="primary" >清除选点</Button>
            <Snackbar open={error} autoHideDuration={3000} onClose={handleErrorClose}>
                <Alert variant="filled" onClose={handleErrorClose} severity="error">
                    地址错误
                </Alert>
                 
            </Snackbar>
            <Snackbar open={fail} autoHideDuration={3000} onClose={handleFailClose}>
                <Alert variant="filled" onClose={handleFailClose} severity="error">
                    请求失败
                </Alert>

            </Snackbar>
        </Grid>

        <Grid container xs={2}></Grid>
    </Grid>
}